import logging
import socket

import cv2
from flask import Flask, render_template, jsonify, request, url_for, redirect
from flask_socketio import SocketIO


class Web_Connection:
    p_img = None
    message = None
    HUD_img = None
    d_img = None

    def __init__(self, name=__name__,
                 template_folder='../templates', static_folder='../static'):
        logging.disable(logging.CRITICAL)
        self.message = None
        self.p_img = None
        self.HUD_img = None
        self.d_img = None
        self.command_queue = None
        self.app = Flask(name, template_folder=template_folder, static_folder=static_folder)
        self.socketio = SocketIO(self.app)  # 添加SocketIO实例
        self.register_routes()

    def gen_frames_HUD(self):
        while True:
            img = self.HUD_img
            if img is None:
                print('Failed to load image.')
                continue
            else:
                ret, buffer = cv2.imencode('.jpg', img)
                frame = buffer.tobytes()
                if not ret:
                    print('Failed to encode image.')

            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

    def gen_frames_GREY(self):
        while True:
            img = self.d_img
            if img is None:
                print('Failed to load image.')
            else:
                ret, buffer = cv2.imencode('.jpg', img)
                frame = buffer.tobytes()
                if not ret:
                    print('Failed to encode image.')

            yield b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n'

    def gen_frames_BW(self):
        while True:
            img = self.p_img
            if img is None:
                print('Failed to load image.')
            else:
                ret, buffer = cv2.imencode('.jpg', img)
                frame = buffer.tobytes()
                if not ret:
                    print('Failed to encode image.')

            yield b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n'

    def register_routes(self):
        @self.app.route('/')
        def arrogant():
            return render_template('/arrogant.html', encoding='gbk')

        @self.app.route('/1')
        def index1():
            return render_template('/1.html', encoding='gbk')

        @self.app.route('/2')
        def index2():
            return render_template('/2.html', encoding='gbk')

        @self.app.route('/3')
        def index3():
            return render_template('/3.html', encoding='gbk')

        @self.socketio.on('/process_button')
        def process_button():
            button_id = request.form['button_id']
            if button_id == 'one':
                return redirect(url_for('index1'))
            elif button_id == 'two':
                return redirect(url_for('index2'))
            else:
                return button_id

        @self.socketio.on('/HUD')
        def HUD():
            response = self.gen_frames_HUD()
            while True:
                self.socketio.emit('frame_hud_data', next(response), namespace='/')
                self.socketio.sleep(0)

        @self.socketio.on('/GREY')
        def GREY():
            response = self.gen_frames_GREY()
            while True:
                self.socketio.emit('frame_grey_data', next(response), namespace='/')
                self.socketio.sleep(0)

        @self.socketio.on('/BW')
        def BW():
            response = self.gen_frames_BW()
            while True:
                self.socketio.emit('frame_bw_data', next(response), namespace='/')
                self.socketio.sleep(0)

        @self.socketio.on('/send')
        def send():
            temple = self.message
            if temple is None:
                return
            data = {
                'time': str(temple[0])[0:223],
                'vgx': str(temple[11]),
                'vgy': str(temple[12]),
                'vgz': str(temple[13]),
                'h': str(temple[17]),
                'pitch': str(temple[8]),
                'roll': str(temple[9]),
                'yaw': str(temple[10]),
                'templ': str(temple[14]),
                'temph': str(temple[15]),
                'bat': str(temple[18]),
                'agx': str(temple[21]),
                'agy': str(temple[22]),
                'agz': str(temple[23]),
            }
            self.socketio.emit('send_data', data, namespace='/')

        @self.socketio.on('/cmd_log')
        def cmd_log():
            temple = self.message
            command = self.command_queue
            if temple is None or command is None:
                return
            cmd = "[" + str(temple[0]) + "]:" + str(command[0])
            data = {
                'cmd': cmd  # 时间 + command
            }
            return jsonify(data)

        @self.socketio.on('/send1')
        def send1():
            temple = self.message
            if temple is None:
                return
            data = {
                'vgx': str(temple[11]),
                'vgy': str(temple[12]),
                'h': str(temple[15]),
                'yaw': str(temple[10]),
            }
            return jsonify(data)

    def run(self):
        hostname = socket.gethostbyname(socket.gethostname())
        self.socketio.run(self.app, host=hostname, port=5000, debug=False)
